namespace SpaceMutinyNameGenerator
{
	using System;
	using System.Threading.Tasks;
	using System.Windows.Forms;

	using Properties;

	using PugLib.Extensions;
	using PugLib.Math;

	public sealed partial class SpaceMutinyNameGeneratorView : Form
	{
		private readonly Task<Names> _names = ThreadingExtensions.StartFunc(GenerateAllNames);
		private Task _task;

		public SpaceMutinyNameGeneratorView()
		{
			InitializeComponent();
		}

		private Names Names
		{
			get { return _names.Result; }
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			_names.ContinueTaskWithUIResult(ex => false, SetInitialState, TaskScheduler.FromCurrentSynchronizationContext());
		}

		private void SetInitialState(Names names)
		{
			this.Text += Resources.TitleSummary + names.MaxNumberOfNames;
			ClickPanel(this, EventArgs.Empty);
		}

		private static Names GenerateAllNames()
		{
			Names names = new Names();
			names.GenerateAllNames();
			return names;
		}

		private void ClickPanel(Object sender, EventArgs e)
		{
			if (_task == null)
			{
				_task = ThreadingExtensions.StartAction(SelectNames);
			}
			else if (_task.IsCompleted)
			{
				_task.Dispose();
				_task = ThreadingExtensions.StartAction(SelectNames);
			}
		}

		private void SelectNames()
		{
			Int32 minItemToShow = PugRandom.GetRandomInRange(1, 100);
			Int32 maxItemToShow = PugRandom.GetRandomInRange(101, 500);
			Int32 itemToShow = PugRandom.GetRandomInRange(minItemToShow, maxItemToShow);
			Int32 startIndex = PugRandom.GetRandomInRange(0, Convert.ToInt32(Names.MaxNumberOfNames - itemToShow));
			maxItemToShow = startIndex + itemToShow;

			for (Int32 i = startIndex; i < maxItemToShow; i++)
			{
				if (i < Names.AllNames.Count)
				{
					Int32 index = i;
					BeginInvoke(new MethodInvoker(() => OnChange(Names.AllNames[index])));
				}
			}
		}

		private void OnChange(String name)
		{
			lblName.Text = name;
			lblName.Refresh();
		}
	}
}